﻿#define Log
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

namespace HotNet{
	public class NetData{
		public int command;
		public string data;
		public DelegateNet result;
		public DelegateNet errorResult;
		public JSON.JSONNode node{
			get{
				return JSON.JSONNode.Parse(data);
			}
		}
		public NetData(int _command,string _data,DelegateNet _result,DelegateNet _errorResult){
			command = _command;
			result = _result;
			data = _data;
			errorResult = _errorResult;
		}
	}
	public class SocketMgr : SingleClass<SocketMgr> {
		public Dictionary<int,NetData> netDatas = new Dictionary<int,NetData>();
		public System.Action<NetData> onSendToNet;
		public void SendMsg(int command,string data,DelegateNet result,DelegateNet errorResult){
			if(netDatas.ContainsKey(command)){
				Debug.Log("存在重复协议");
			}else{
				Debug.Log(string.Format("准备发送协议:{0} 数据:{1}",command,data.ToString()));
				var ndata = new NetData(command,data,result,errorResult);
				netDatas.Add(command,ndata);
				SendToNet(ndata);
			}
		}

		private void SendToNet(NetData data){
			if(onSendToNet != null)
				onSendToNet(data);
		}

		public void OnRecvMsg(int command,string data,bool iserror){
			if(netDatas.ContainsKey(command)){
				Debug.Log(" recv command:"+command+" data:"+data+" iserror :"+iserror);
				netDatas[command].data = data;
				if(iserror)
					netDatas[command].errorResult(data);
				else
					netDatas[command].result(data);

				netDatas.Remove(command);
			}else
				OnPush(command,data);
		}
		

		void OnPush(int command,string data){
			
		}
	}
}